package com.wu.wechat.controller;

import com.wu.common.exception.WexinReqException;
import com.wu.common.utils.RedisUtils;
import com.wu.wechat.util.JwMenuAPI;
import com.wu.common.utils.OConvertUtils;
import com.wu.common.utils.Result;
import com.wu.entity.weixin.po.WeixinButton;
import com.wu.entity.weixin.po.WeixinMenu;
import com.wu.wechat.service.WeixinMenuService;
import com.wu.wechat.util.WxErrCodeUtil;
import io.swagger.v3.oas.annotations.Operation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/wechat/menu")
public class MenuController {

    @Autowired
    private WeixinMenuService weixinMenuService;


    @RequestMapping(value="synToWeixin/{id}",method={RequestMethod.GET, RequestMethod.POST})
    @Operation(summary = "同步微信菜单")
    @PreAuthorize("hasAuthority('sys:user:page')")
    public Result synToWeixin(@PathVariable("id") String jwid){
        //获取jwid
        //根据jwid获取一级菜单
        WeixinMenu queryFristMenu=new WeixinMenu();
        queryFristMenu.setFatherId("");
        queryFristMenu.setJwid(jwid);
        List<WeixinMenu> firstMenus=weixinMenuService.queryMenusByJwid(queryFristMenu);
        //获取token方法替换
        String accessToken = RedisUtils.getWxAccount(jwid).getAccountaccesstoken();
        if(OConvertUtils.isEmpty(accessToken)){
            return Result.error("未获取到公众号accessToken");
        }
        //判断如果菜单为空的话，则调用删除菜单的接口
        if(firstMenus.size()==0){
            return Result.ok("该公众号未定义菜单");
        }
        //获取二级菜单
        List<WeixinButton> resultList=new ArrayList<WeixinButton>();
        for(int i=0;i<firstMenus.size();i++){
            WeixinMenu queryChildMenu=new WeixinMenu();
            queryChildMenu.setJwid(jwid);
            queryChildMenu.setFatherId(firstMenus.get(i).getId());
            List<WeixinMenu> childMenus=weixinMenuService.queryMenusByJwid(queryChildMenu);
            if(childMenus.size()==0){
                //组装菜单接口的参数结构体
                resultList.add(combineBtn(firstMenus.get(i)));
            }else{
                //组装一级菜单名称
                WeixinButton wxButton = new WeixinButton();
                wxButton.setName(firstMenus.get(i).getMenuName());
                //组装二级菜单接口的参数结构体
                List<WeixinButton> childlist=new ArrayList<WeixinButton>();
                for(int m=0;m<childMenus.size();m++){
                    childlist.add(combineBtn(childMenus.get(m)));
                }
                wxButton.setSub_button(childlist);
                resultList.add(wxButton);
            }
        }
        try {
            return Result.ok(JwMenuAPI.createMenu(accessToken, resultList));
        } catch (WexinReqException e) {
            JSONObject code=JSONObject.fromObject(e.getMessage());
            String errcode=code.getString("errcode");
            //author:sunkai--date:2018-09-26--for:菜单同步错误返回码信息转义
            String msg = WxErrCodeUtil.testErrCode(errcode);
            e.printStackTrace();
            return Result.error("微信菜单同步失败！"+msg);
        }
    }

    /**
     * @功能：组装菜单接口的参数结构体
     * @param weixinMenu
     */
    private WeixinButton combineBtn(WeixinMenu weixinMenu) {
        WeixinButton wxButton=new WeixinButton();
        //网页链接类
        if("view".equals(weixinMenu.getMenuType())){
            wxButton.setName(weixinMenu.getMenuName());
            wxButton.setType(weixinMenu.getMenuType());
            wxButton.setUrl(weixinMenu.getUrl());
        }
        //消息触发类
        if("click".equals(weixinMenu.getMenuType())){
            wxButton.setName(weixinMenu.getMenuName());
            wxButton.setType(weixinMenu.getMenuType());
            wxButton.setKey(weixinMenu.getMenuKey());
        }
        //小程序类
        if("miniprogram".equals(weixinMenu.getMenuType())){
            wxButton.setName(weixinMenu.getMenuName());
            wxButton.setType(weixinMenu.getMenuType());
            wxButton.setUrl(weixinMenu.getUrl());
            wxButton.setAppid(weixinMenu.getMiniprogramAppid());
            wxButton.setPagepath(weixinMenu.getMiniprogramPagepath());
        }
        return wxButton;
    }
}
